import os
from nicegui import ui, app
import mysql.connector
from mysql.connector import Error
import datetime
import uuid

# 数据库配置 - 从环境变量读取（关键！）
DB_CONFIG = {
    'host': os.environ.get('DB_HOST'),
    'user': os.environ.get('DB_USER'),
    'password': os.environ.get('DB_PASSWORD'),
    'database': os.environ.get('DB_NAME'),
    'port': int(os.environ.get('DB_PORT', 3306))
}

def get_db_connection():
    """建立数据库连接"""
    connection = None
    try:
        connection = mysql.connector.connect(**DB_CONFIG)
        if connection.is_connected():
            return connection
    except Error as e:
        print(f"数据库连接错误: {e}")
        return None

def generate_session_token(user_id):
    """生成会话令牌并存储到数据库"""
    connection = get_db_connection()
    if not connection:
        return None
        
    try:
        cursor = connection.cursor()
        session_id = str(uuid.uuid4())
        expires_at = datetime.now() + timedelta(days=7)  # 7天有效期
        
        # 假设已创建sessions表存储会话信息
        cursor.execute(
            "INSERT INTO sessions (session_id, user_id, expires_at) VALUES (%s, %s, %s)",
            (session_id, user_id, expires_at)
        )
        connection.commit()
        return session_id
    except Error as e:
        print(f"会话创建错误: {e}")
        return None
    finally:
        if connection and connection.is_connected():
            cursor.close()
            connection.close()

def verify_session(session_id):
    """验证会话令牌是否有效"""
    connection = get_db_connection()
    if not connection:
        return None
        
    try:
        cursor = connection.cursor(dictionary=True)
        cursor.execute(
            "SELECT * FROM sessions WHERE session_id = %s AND expires_at > %s",
            (session_id, datetime.now())
        )
        session = cursor.fetchone()
        return session['user_id'] if session else None
    except Error as e:
        print(f"会话验证错误: {e}")
        return None
    finally:
        if connection and connection.is_connected():
            cursor.close()
            connection.close()

def clear_session(session_id):
    """清除会话"""
    connection = get_db_connection()
    if not connection:
        return
        
    try:
        cursor = connection.cursor()
        cursor.execute("DELETE FROM sessions WHERE session_id = %s", (session_id,))
        connection.commit()
    except Error as e:
        print(f"清除会话错误: {e}")
    finally:
        if connection and connection.is_connected():
            cursor.close()
            connection.close()

# MicroPay相关数据库操作函数
def get_micropay_entries():
    """获取所有微支付条目"""
    connection = get_db_connection()
    if not connection:
        return []
        
    try:
        cursor = connection.cursor(dictionary=True)
        cursor.execute("SELECT * FROM micropay")
        return cursor.fetchall()
    except Error as e:
        print(f"查询微支付数据错误: {e}")
        return []
    finally:
        if connection and connection.is_connected():
            cursor.close()
            connection.close()

def add_micropay_entry(name, url, entry_id):
    """添加新的微支付条目"""
    connection = get_db_connection()
    if not connection:
        return False
        
    try:
        cursor = connection.cursor()
        cursor.execute(
            "INSERT INTO micropay (name, url, id) VALUES (%s, %s, %s)",
            (name, url, entry_id)
        )
        connection.commit()
        return True
    except Error as e:
        print(f"添加微支付条目错误: {e}")
        return False
    finally:
        if connection and connection.is_connected():
            cursor.close()
            connection.close()

def delete_micropay_entry(entry_id):
    """删除微支付条目"""
    connection = get_db_connection()
    if not connection:
        return False
        
    try:
        cursor = connection.cursor()
        cursor.execute("DELETE FROM micropay WHERE id = %s", (entry_id,))
        connection.commit()
        return cursor.rowcount > 0  # 返回是否有记录被删除
    except Error as e:
        print(f"删除微支付条目错误: {e}")
        return False
    finally:
        if connection and connection.is_connected():
            cursor.close()
            connection.close()

@ui.page('/')
def main_page():
    # 检查是否已有有效会话
    session_id = app.storage.user.get('session_id')
    if session_id and verify_session(session_id):
        ui.navigate.to('/home')
        return
        
    ui.dark_mode()
    with ui.card().classes('absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2'):
        with ui.row():
            ui.markdown("# 欢迎回来")
            with ui.card():
                ui.label("请登录以继续")
                username_input = ui.input('ID')  # 假设输入的是用户ID（对应Users表的ID）
                password_input = ui.input('令牌').props('type=password')
                ui.link('没有ID? 现在注册！', '/register')
                
                async def handle_login():
                    """处理登录逻辑"""
                    connection = get_db_connection()
                    if not connection:
                        ui.notify("数据库连接失败", color="negative")
                        return
                    
                    try:
                        cursor = connection.cursor(dictionary=True)
                        # 查询用户（Users表用大写ID）
                        cursor.execute(
                            "SELECT * FROM Users WHERE ID = %s",
                            (username_input.value,)
                        )
                        user = cursor.fetchone()
                        if user:
                            # 查询令牌（Tokens表用tokenuserid关联）
                            cursor.execute(
                                "SELECT * FROM Tokens WHERE tokenuserid = %s",
                                (user['ID'],)  # 用Users表的ID匹配tokenuserid
                            )
                            token = cursor.fetchone()
                            if token and token['tokens'] == password_input.value:
                                # 生成会话令牌
                                session_id = generate_session_token(user['ID'])
                                if session_id:
                                    # 存储会话ID到Cookie
                                    app.storage.user['session_id'] = session_id
                                    ui.notify(f"登录成功！用户ID: {user['ID']}", color="positive")
                                    ui.navigate.to('/home')
                                else:
                                    ui.notify("会话创建失败", color="negative")
                            else:
                                ui.notify("令牌不正确", color="warning")
                        else:
                            ui.notify("用户不存在", color="negative")
                    except Error as e:
                        ui.notify(f"查询错误: {str(e)}", color="negative")
                    finally:
                        if connection and connection.is_connected():
                            cursor.close()
                            connection.close()
                
                ui.button('登录', on_click=handle_login).props('color=primary')

@ui.page('/register')
def register_page():
    ui.dark_mode()
    with ui.card().classes('absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2'):
        with ui.column():
            ui.markdown("# 啊哦，页面被咬了")
            ui.link('返回', '/')

@ui.page('/home')
def home_page():
    # 验证会话
    session_id = app.storage.user.get('session_id')
    if not session_id or not verify_session(session_id):
        ui.navigate.to('/')
        return
        
    ui.dark_mode()
    with ui.card().classes('absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2'):
        with ui.column():
            ui.markdown("# 主页")
            with ui.card().style('background-color: #e3f2fd;'):
                ui.markdown("### 智造加 Studios.")
            
            ui.label("我们的服务")

            with ui.column():
                with ui.card().style('background-color: #f0f4c3;'):
                    ui.markdown("#### Micro Pay")
                    ui.markdown("一个基于区块链的微支付系统，支持多种加密货币支付。")
                    ui.button('访问 Micro Pay', on_click=lambda: ui.navigate.to('/MicroPay')).props('color=primary')
            
            def handle_logout():
                """处理登出"""
                session_id = app.storage.user.get('session_id')
                if session_id:
                    clear_session(session_id)
                    del app.storage.user['session_id']
                ui.navigate.to('/')
            
            ui.button('登出', on_click=handle_logout).props('color=negative')

@ui.page('/MicroPay')
def micro_pay_page():
    # 验证会话
    session_id = app.storage.user.get('session_id')
    user_id = verify_session(session_id) if session_id else None
    if not user_id:
        ui.navigate.to('/')
        return
        
    ui.dark_mode()
    with ui.card().classes('absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-3/4 max-w-3xl'):
        ui.markdown("# Micro Pay 微支付系统")
        
        # 显示用户信息
        ui.label(f"当前用户 ID: {user_id}")
        
        # 软件列表区域
        software_list = ui.column().classes('w-full mt-4')
        ui.label("相关软件:").classes('text-lg font-bold mt-4')
        
        # 从数据库获取用户相关的软件信息（使用micropay表和id字段）
        def load_software():
            connection = get_db_connection()
            if not connection:
                ui.notify("数据库连接失败", color="negative")
                return []
                
            try:
                cursor = connection.cursor(dictionary=True)
                # 关键修复：使用id字段而不是user_id
                cursor.execute(
                    "SELECT name, url FROM micropay WHERE id = %s",
                    (user_id,)
                )
                return cursor.fetchall()
            except Error as e:
                print(f"查询软件信息错误: {e}")
                ui.notify("获取软件信息失败", color="negative")
                return []
            finally:
                if connection and connection.is_connected():
                    cursor.close()
                    connection.close()
        
        # 加载并显示软件
        softwares = load_software()
        if softwares:
            for software in softwares:
                with software_list:
                    # 关键修复：样式语法错误，将 'w-full' 改为 'width: 100%'
                    with ui.card().style('background-color: #e8f5e9; width: 100%'):
                        ui.markdown(f"### {software['name']}")
                        ui.link("下载软件", software['url']).props('color=primary')
        else:
            ui.label("暂无相关软件信息").classes('text-gray-500')
        
        # 返回主页按钮
        ui.button('返回主页', on_click=lambda: ui.navigate.to('/home')).props('mt-4')

# 启动配置（关键修改）
if __name__ in {"__main__", "__mp_main__"}:
    # 从环境变量获取端口，Render 会自动分配
    port = int(os.environ.get('PORT', 8080))
    # 启动应用
    ui.run(
        storage_secret=os.environ.get('STORAGE_SECRET', 'afff001a1l2'),  # 建议从环境变量获取
        host='0.0.0.0',  # 允许外部访问
        port=port,
        reload=False  # 生产环境禁用自动重载
    )